package io.renren.htby.utils;

import java.util.UUID;

/**
 * 从 core 的 Lang文件中，把生成UUID摘出来单独使用。
 * @author liufengyuan
 * @Date 2016年8月29日 上午11:49:13
 */
public class NewLang {
	
	 /**
     * 得到随机的22位UUID
     * @return 22位UUID
     */
    public static String getUUID() {
        StringBuilder sb = new StringBuilder("0");
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        sb.append(uuid);
        uuid = hexTo64(sb.toString());
     
        //System.out.println("uuid:"+uuid);
        return uuid;
    }
	
	/** 下面代码用于将36位的UUID字符串转为22位的字符串，提升系统运行效率 */
    private static final char[] CHAR_MAP;
    static {
        CHAR_MAP = new char[64];
        for (int i = 0; i < 10; i++) {
            CHAR_MAP[i] = (char) ('0' + i);
        }
        for (int i = 10; i < 36; i++) {
            CHAR_MAP[i] = (char) ('a' + i - 10);
        }
        for (int i = 36; i < 62; i++) {
            CHAR_MAP[i] = (char) ('A' + i - 36);
        }
        CHAR_MAP[62] = '_';
        CHAR_MAP[63] = '-';
    }
	
	 /**
     * 将16进制字符串转换为64进制
     * @param hex 16进制字符串
     * @return 64进制字符串
     */
    public static String hexTo64(String hex) {
        StringBuilder r = new StringBuilder();
        int index = 0;
        final int size = 3;
        int[] buff = new int[size];
        int l = hex.length();
        for (int i = 0; i < l; i++) {
            index = i % size;
            buff[index] = Integer.parseInt("" + hex.charAt(i), 16);
            if (index == 2) {
                r.append(CHAR_MAP[buff[0] << 2 | buff[1] >>> 2]);
                r.append(CHAR_MAP[(buff[1] & size) << 4 | buff[2]]);
            }
        }
        //System.out.println("r.toString():" + r.toString());
        return r.toString();
    }
}
